package com.free.semantic.core.common.serializeimpl.baseimpl;

import com.free.semantic.core.Context;
import com.free.semantic.core.funcimpl.BaseFuncImpl;
import com.free.semantic.model.util.CommandExecutor;
import com.free.semantic.model.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpRequestImpl extends BaseFuncImpl {

    private List<String> commandLine;

    public HttpRequestImpl(List<String> commandLine) {
        this.commandLine = commandLine;
    }

    @Override
    public void calculate(Context context) {
        List<String> req = commandLine.subList(1, commandLine.size());
        List<String> sourceObjList = getRelationItem().getSourceObjList();
        Map<String, Object> map = new HashMap<>();
        for (String s : sourceObjList) {
            List<Object> listValue = context.getListValue(s);
            if (listValue.size() == 1) {
                map.put(s, listValue.get(0));
                continue;
            }
            map.put(s, listValue);
        }
        List<String> fill = new ArrayList<>();
        for (String s : req) {
            fill.add(StringUtils.replaceVariables(s, map));
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (String s : fill) {
            stringBuilder.append(s);
            stringBuilder.append("\n");
        }
        CommandExecutor.CommandResult commandResult = CommandExecutor.executeCommand(stringBuilder.toString());
        if (commandResult.isSuccess()) {
            List<String> output = commandResult.getOutput();
            context.setValue(getRelationItem().getDestObject(), output.get(output.size() - 1));
        } else {
            throw new RuntimeException(commandResult.getOutputString());
        }
    }


}
